import type { MenuResponse, MenuStructure } from "@/api/menu.ts"
import {
  addMenuApi,
  deleteMenuApi,
  getMenuListApi,
  updateMenuApi
} from "@/api/menu.ts"

export const useMenuStore = defineStore("menu", () => {
  const state = reactive<MenuResponse>({
    menus: []
  })

  const getMenuList = async () => {
    const res = await getMenuListApi()
    const { data } = res
    state.menus = data.menus
  }

  const addMenu = async (menu: MenuStructure) => {
    const res = await addMenuApi(menu)
    if (res.code === 200) {
      getMenuList()
    }
  }

  const updateMenu = async (menu: MenuStructure) => {
    const res = await updateMenuApi(menu)
    if (res.code === 200) {
      getMenuList()
    }
  }

  const deleteMenu = async (id: number) => {
    const res = await deleteMenuApi(id)
    if (res.code === 200) {
      getMenuList()
    }
  }

  return {
    state,
    getMenuList,
    addMenu,
    updateMenu,
    deleteMenu
  }
})
